package com.android.support.lib.universal.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

/**
 * 获取网络地址，和设备号 权限： <uses-permission android:name="android.permission.INTERNET"/>
 * <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 * <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
 * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
 * <uses-permission android:name="android.permission.READ_PHONE_STATE" />//读取设备号的权限
 * 使用：
 * Utilmac utilmac=new Utilmac();
 * utilmac.getLocalHostIp4()//获取IP4地址 MacUtil.getLocalHostIp6()//获取IP6地址
 * utilmac.getLocalMacAddress(this)//this是Contex上下文，获取mac地址
 * 
 * @author 彭治铭
 *
 */
public class Utilmac {
	/**
	 * 获取Ip4地址
	 * 
	 * @return
	 */
	public  String getLocalHostIp4() {
		String ipaddress = "";
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			// 遍历所用的网络接口
			while (en.hasMoreElements()) {
				NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
				Enumeration<InetAddress> inet = nif.getInetAddresses();
				// 遍历每一个接口绑定的所有ip
				while (inet.hasMoreElements()) {
					InetAddress ip = inet.nextElement();
					if (!ip.isLoopbackAddress()
							&& ip instanceof Inet4Address) {
						return ipaddress = ip.getHostAddress();
					}
				}

			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return ipaddress;

	}

	/**
	 * 获取IP6地址
	 * 
	 * @return
	 */
	public  String getLocalHostIp6() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return null;
	}

	/**
	 * 通过wifi 获取mac地址
	 * 
	 * @param context
	 * @return
	 */
	public  String getLocalMacAddress(Context context) {
		WifiManager wifi = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();
	}
	
	/**
	 * 获取设备号，无效返回000000000000000
	 * 据测试：所有的设备都可以返回一个 TelephonyManager.getDeviceId()
	 * @param context
	 * @return
	 */
	public  String getDeviceId(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		tm.getDeviceId();
		return tm.getDeviceId();
	}
}
